package com.example.demo.controller;

import com.example.demo.constant.Constant;
import com.example.demo.entity.AjaxResult;
import com.example.demo.service.FirmwareUpgradeService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/firmwareUpgrade")
public class FirmwareUpgradeController {

    @Value("${demo.dirPath}")
    private String dirPath;
    @Value("${server.servlet.context-path}")
    private String ctxPath;
    @Value("${env.name}")
    private String envName;
    @Autowired
    private FirmwareUpgradeService firmwareUpgradeService;
    @GetMapping("/list")
    public String index(Model model){
        // 表格内容的遍历
        List<Map<String, Object>> flist = firmwareUpgradeService.findAll();
        model.addAttribute("flist", flist);
        model.addAttribute("ctxPath", ctxPath);
        model.addAttribute("envName", envName);
        return "index";
    }

    @GetMapping("/add")
    public String add(Model model){
        // 表格内容的遍历
        model.addAttribute("_data", new HashMap<>());
        model.addAttribute("ctxPath", ctxPath);
        model.addAttribute("envName", envName);
        return "page/update_el";
    }
    @GetMapping("/update")
    public String update(int id, Model model){
        // 表格内容的遍历
        Map _data = firmwareUpgradeService.findById(id);
        model.addAttribute("_data", _data);
        model.addAttribute("ctxPath", ctxPath);
        model.addAttribute("envName", envName);
        return "page/update_el";
    }
    @GetMapping("/delete")
    public String delete(int id, Model model){
        // 表格内容的遍历
        firmwareUpgradeService.deleteById(id);
        List<Map<String, Object>> flist = firmwareUpgradeService.findAll();
        model.addAttribute("flist", flist);
        model.addAttribute("ctxPath", ctxPath);
        model.addAttribute("envName", envName);
        return "page/list";
    }

    @PostMapping(value = "/save", consumes = "application/json")
    @ResponseBody
    public AjaxResult save(@RequestBody Map<String, Object> data, Model model){
        firmwareUpgradeService.save(data);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", data);
        return ajax;
    }

    @GetMapping({"/checkVersion"})
    @ResponseBody
    public AjaxResult checkVersion(@RequestParam Map<String, Object> param) {
        int version = 0;
        if (param.get("projectCode") != null){
            version = Integer.valueOf(param.get("version").toString());
            param.remove("version");
            param.remove("orderBy");
        }
        List<Map<String, Object>> list = this.firmwareUpgradeService.findByMap(param);
        AjaxResult ajax = AjaxResult.success();
        if(list.size() >0){
            Map<String, Object> data = list.get(0);
            String maxVersion = data.get("version") != null ?data.get("version").toString() : "0";
            if (Integer.valueOf(maxVersion).intValue() > version)
                ajax.put("data", data);
        }
        return ajax;
    }

    @GetMapping({"/usefulVersion"})
    @ResponseBody
    public AjaxResult getUsefulVersion(@RequestParam Map<String, Object> param) {
//        project_code
//        model
        String listSql = String.format("select * from firmware_upgrade where project_code='%s' and model='%s' order by version desc limit 2",
                param.get("project_code"), param.get("model"));
        String maxSql = String.format("select max(force_version) version from firmware_upgrade where project_code='%s' and model='%s'",
                param.get("project_code"), param.get("model"));
        List<Map<String, Object>> list = this.firmwareUpgradeService.findBySql(listSql);
        List<Map<String, Object>> maxVersion = this.firmwareUpgradeService.findBySql(maxSql);
        Map<String, Object> data = new HashMap<>();
        if(list.size() > 0){
            if(maxVersion.size() > 0 && list.size() > 1){
                int max = Integer.valueOf(maxVersion.get(0).get("version").toString());
                int backVrsion = Integer.valueOf(list.get(1).get("version").toString());
                if(max < backVrsion){
                    data.put("backVersion", list.get(1));
                }
            }
            data.put("newVersion", list.get(0));
        }

        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", data);
        return ajax;
    }

    @GetMapping({"/findByMap"})
    @ResponseBody
    public AjaxResult findByMap(@RequestParam Map<String, Object> param) {
        List<Map<String, Object>> data = this.firmwareUpgradeService.findByMap(param);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", data);
        return ajax;
    }

    @GetMapping("/downloadByProcode")
    public ResponseEntity<byte[]> fileDownload(String projectCode){
        Map<String, Object> data = firmwareUpgradeService.findByProjectCode(projectCode);
        String filename = "";
        if(data == null || data.isEmpty() || data.get("file_name") == null || "".equals(data.get("file_name"))){
            return new ResponseEntity<byte[]>(("请维护" + projectCode + "的附件信息").getBytes(),
                    HttpStatus.EXPECTATION_FAILED);
        }
        filename = data.get("file_name").toString();
        //指定要下载的文件根路径
        //创建该文件对象
        File file = new File(dirPath + File.separator + filename);
        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        //通知浏览器以下载方式打开
        headers.setContentDispositionFormData("attachment",filename);
        //定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file),
                    headers, HttpStatus.OK);
        }
        catch (Exception e) {e.printStackTrace();
            return new ResponseEntity<byte[]>(e.getMessage().getBytes(),
                    HttpStatus.EXPECTATION_FAILED);
        }
    }
}
